Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

// checkColumn
Ext.grid.CheckColumn = function(config){  
    Ext.apply(this, config);  
    if (!this.id) {  
        this.id = Ext.id();  
    }  
    this.renderer = this.renderer.createDelegate(this);  
};  
  
Ext.grid.CheckColumn.prototype = {  
    init: function(grid){  
        this.grid = grid;  
        this.grid.on('render', function(){  
            var view = this.grid.getView();  
            view.mainBody.on('mousedown', this.onMouseDown, this);  
        }, this);  
    },  
    onMouseDown: function(e, t){  
        if (t.id == this.id) {  
            e.stopEvent();  
            var index = this.grid.getView().findRowIndex(t);//行号  
            var cindex = this.grid.getView().findCellIndex(t);//列号 
            var record = this.grid.store.getAt(index);//行记录  
            var field = this.grid.colModel.getDataIndex(cindex);//列名  
            var value = !record.data[this.dataIndex];//点击后，获得当前checkbox值的相反值  
            var store = this.grid.store;
            record.set(this.dataIndex, value);//设定checkbox被选择时候的值  
            //事件的参数  
            var e = {  
               grid: this.grid,  
               record: record,  
               field: field,   
               originalValue: record.data[this.dataIndex],  
               value: !record.data[this.dataIndex],  
               row: index,  
               store: store,
               column: cindex  
           };  
  
            //向上查询descripe2相同，查4位
            var upFlag = true; //向上标记，为1时终止
            var downFlag = true; // 向下标记，为1时终止
            var result = new Array(4); //最多能找到4个
            var count = 0; //总计
            var i = 0; //向上
            var j = 0; //向下
            //alert(index);
            
            //先向上查询
           	while(upFlag && index - i >= 0){
           		if(store.getAt(index-i).get('describe2') === store.getAt(index).get('describe2')){
           			result[count++] = index-i;
           		}else{
           			upFlag = false;
           		}
           		//alert("i:" +i);
           		i++;
           	}
           	
            //向下查询
           	//alert("total: "+store.getCount());
           	while(downFlag && index + j < store.getCount()){
           		if(store.getAt(index+j).get('describe2') === store.getAt(index).get('describe2')){
           			result[count++] = index+j;
           		}else{
           			downFlag = false;
           		}
           		//alert("j:" +j);
           		j++;
           	}
           	
           	//遍历result， 将结果中的行设置value
           	//value为false的时候不处理，否则其他行会被置为true
           	if(value){
           		for(var k=0; k<count && result[k]!==null ;k++){
           			this.grid.store.getAt(result[k]).set(field,!value);
           		} 
           	}
           	this.grid.store.getAt(index).set(field,value);
           	
           	
        }  
    },  
    renderer: function(v, p, record){  
        p.css += ' x-grid3-check-col-td';  
        return '<div id="' + this.id + '" class="x-grid3-check-col' + (v ? '-on' : '') + '">&#160;</div>';  
    }  
};


var checkColumn = new Ext.grid.CheckColumn({  
                   header: "选择",  
                   dataIndex: 'checkSelect',  
                   width: 10  
        });  



/*
var addForm = new Ext.form.FormPanel({ 
id: 'addForm', 
renderTo:'formPanel',
width: 1200, 
height: 300, 
//样式 
bodyStyle: 'margin:3px 3px 3px 3px', 
frame: true, 
xtype: 'filedset', 
items: 
[{ xtype: 'fieldset', 
title: '地址信息', 
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[{
layout:"column",
items:[
{
	columnWidth : .2, // 该列有整行中所占百分比
    layout : "form",
    labelWidth: 60,
    items : [{
		xtype: 'numberfield',
		id: 'tel', 
		name: 'tel', 
		fieldLabel: '大类因素',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false,  
		anchor:'96%' 
	}]
},
{ 
	columnWidth : .2, // 该列有整行中所占百分比
    layout : "form",
    labelWidth: 60,
    items : [{
		xtype: 'numberfield',
		id: 'fax', 
		name: 'fax', 
		fieldLabel: '子类因素',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'
	}]
},
{ 
	columnWidth : .2, // 该列有整行中所占百分比
    layout : "form",
    labelWidth: 60,
    items : [{
		xtype: 'numberfield',
		id: 'fax1', 
		name: 'fax', 
		fieldLabel: '因素说明',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%' 
	}]
},
{ 
	columnWidth : .3, // 该列有整行中所占百分比
    layout : "form",
    labelWidth: 20, 
    items : [
    {
		xtype: 'numberfield',
		id: 'fax00', 
		name: 'fax', 
		fieldLabel: 'A',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%' 
	},
	{
		xtype: 'numberfield',
		id: 'fax01', 
		name: 'fax', 
		fieldLabel: 'B',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'  
	},
	{
		xtype: 'numberfield',
		id: 'fax02', 
		name: 'fax', 
		fieldLabel: 'C',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'  
	},
	{
		xtype: 'numberfield',
		id: 'fax03', 
		name: 'fax', 
		fieldLabel: 'D',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'  
	},
	{
		xtype: 'numberfield',
		id: 'fax04', 
		name: 'fax', 
		fieldLabel: 'E',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'  
	},
	{
		xtype: 'numberfield',
		id: 'fax05', 
		name: 'fax', 
		fieldLabel: 'F',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%'  
	}
	]
},
{ 
	columnWidth : .1, // 该列有整行中所占百分比
    layout : "form",
    labelWidth: 80, 
    items : [{
		xtype: 'numberfield',
		id: 'fax3', 
		name: 'fax', 
		fieldLabel: '绝对权重(%)',
		allowBlank: true,  
		allowDecimals:true,               
		allowNegative:false, 
		anchor:'96%' 
	}]
} 
]
}]
}]
});
*/

function getBodyWidth(){  
    return document.body.clientWidth-15;  
}  
  

var _bodyWidth = getBodyWidth() - 20;  
var _columns = 6;  
var _perWidth = _bodyWidth/_columns;  
    
var addForm=new Ext.FormPanel({   
        id:'addForm',  
        frame:true,  
        layout:'table',   
        style:'height:100%,width:100%',  
        layoutConfig: {columns:_columns},  
        //title:'TableForm',
        defaults:{width:_perWidth}, 
        items:[
	        {
			    items:[{
				    	layout : "form",
					    labelWidth: 60,
					    items : [{
							xtype: 'textfield',
							id: 'describe1', 
							name: 'describe1', 
							fieldLabel: '大类因素',
							allowBlank: false,
							blankText:'请输入大类因素',    
							anchor:'96%' 
						}]
				}]
		    },
		    {
			    items:[{
				    	layout : "form",
					    labelWidth: 60,
					    items : [{
							xtype: 'textfield',
							id: 'describe2', 
							name: 'describe2', 
							fieldLabel: '子类因素',
							allowBlank: false,
							blankText:'请输入子类因素',     
							anchor:'96%' 
						}]
				}]
		    },
		    {
			    items:[{
				    	layout : "form",
					    labelWidth: 60,
					    items : [{
							xtype: 'textfield',
							id: 'describe3', 
							name: 'describe3', 
							fieldLabel: '因素说明',
							allowBlank: true,   
							anchor:'96%' 
						}]
				}]
		    },
		     {
			    items:[{
				    	layout : "form",
					    labelWidth: 20,
					    items : [{
							xtype: 'textfield',
							id: 'itemDescribe1', 
							name: 'itemDescribe1', 
							fieldLabel: 'A',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemDescribe2', 
							name: 'itemDescribe2', 
							fieldLabel: 'B',
							allowBlank: true,   
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemDescribe3', 
							name: 'itemDescribe3', 
							fieldLabel: 'C',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemDescribe4', 
							name: 'itemDescribe4', 
							fieldLabel: 'D',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemDescribe5', 
							name: 'itemDescribe5', 
							fieldLabel: 'E',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemDescribe6', 
							name: 'itemDescribe6', 
							fieldLabel: 'F',
							allowBlank: true,   
							anchor:'96%' 
							}
						]
				}]
		    },
		    {
			    items:[{
				    	layout : "form",
					    labelWidth: 40,
					    items : [{
							xtype: 'textfield',
							id: 'itemValue1', 
							name: 'itemValue1', 
							fieldLabel: '得分',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemValue2', 
							name: 'itemValue2', 
							fieldLabel: '得分',
							allowBlank: true,   
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemValue3', 
							name: 'itemValue3', 
							fieldLabel: '得分',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemValue4', 
							name: 'itemValue4', 
							fieldLabel: '得分',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemValue5', 
							name: 'itemValue5', 
							fieldLabel: '得分',
							allowBlank: true,    
							anchor:'96%' 
							},
							{
							xtype: 'textfield',
							id: 'itemValue6', 
							name: 'itemValue6', 
							fieldLabel: '得分',
							allowBlank: true,   
							anchor:'96%' 
							}
						]
				}]
		    },
		    {
			    items:[{
				    	layout : "form",
					    labelWidth: 80,
					    items : [{
							xtype: 'numberfield',
							id: 'itemWeight', 
							name: 'itemWeight', 
							fieldLabel: '绝对权重(%)',
							allowBlank: false,
							blankText:'请输入绝对权重',   
							allowDecimals:true,               
							allowNegative:false,  
							anchor:'96%' 
						}]
				}]
		    }
		 ],
	buttons:[{text:'添加',handler:func_submit_onclick},
	{text:'完成'}
	]   
    });  
      
   // addForm.addButton({text:'添加',handler:func_submit_onclick});  
   // addForm.addButton({text:'cancel'});  
      
    //addForm.render(Ext.getBody()); 
    
var config={
    title:"提示",
    width:240,
    msg:'<div align="center">操作成功！</div>',
    closable:false,
    buttons:{yes:'添加新的大类',no:'继续添加子类'},
    fn: function(btn){
    	//alert('单击的按钮id是：'+btn);
    	if(btn == 'no'){
    		var nowDescribe1 = Ext.getCmp('describe1').getValue();
    		addForm.form.reset();
    		Ext.getCmp('describe1').setValue(nowDescribe1);
    		grid.store.reload(); 
    	}
    	else if(btn == 'yes'){
    		addForm.form.reset();
    		grid.store.reload(); 
    	}
    }
    //icon:Ext.MessageBox.Question
}



function func_submit_onclick(){  
    if(addForm.form.isValid()){
		addForm.form.doAction('submit', { 
			url : 'model/addQua.do',
			method : 'POST',
			success : function() {
				var msgbox = Ext.MessageBox.show(config); 
				msgbox.getDialog().moveTo(100, 100); 
				//setPosition(event.x - 300 ,event.y + 100); 
				//Ext.Msg.alert("提示", "操作成功！");
				grid.store.reload(); 
			},
			failure : function() {
				Ext.MessageBox.alert("请求异常！");
			}
		});
	}    
}  

var fm = Ext.form;

//Gridpanel
var cm=new Ext.grid.ColumnModel([
{header:'流水号',dataIndex:'serialNo',hidden:true,
editor: new fm.TextField({allowBlank: false,editable:false,readOnly:true})
} ,
{header:'大类因素',
	sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('describe1'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('describe1');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('describe1')) {
                            i++;
                        }
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';line-height:' + height + ';"';
                    }
                    return first ? value : '';
                }, 
	dataIndex:'describe1',
	width:60,
	editor: new fm.TextField({
                allowBlank: false
            })
    },
{header:'子类因素',
			sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('describe2'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('describe2');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('describe2')) {
                            i++;
                        }
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';line-height:' + height + ';"';
                    }
                    return first ? value : '';
                }, 
		dataIndex:'describe2',
		width:160,
		editor: new fm.TextField({
                allowBlank: false
            })	
},
  
{header:'选项说明',
dataIndex:'itemDescribe',
width:300,
renderer: function (value, metadata, record){
	metadata.attr = 'style="white-space:normal;"'; 
	return value; 
},
editor: new fm.TextField({
                allowBlank: false
})
},

{header:'选项得分',
dataIndex:'itemValue',
width:20,
editor: new fm.NumberField({
                allowBlank: false,
                allowNegative: false
            })
},
{header:'绝对权重(%)',
	sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('itemWeight') || 
                    	store.getAt(rowIndex).get('describe2') !== store.getAt(rowIndex-1).get('describe2'),
                    	
                    last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('itemWeight');
                   // alert("first: "+first+"last: "+last);
                    
                    var first1 = true;
                    var last1 = true;
                    if(rowIndex >=1 && rowIndex < store.getCount()-2){
                 	  var first1 = !rowIndex || value !== store.getAt(rowIndex ).get('itemWeight') || 
                  	  store.getAt(rowIndex+1).get('describe2') !== store.getAt(rowIndex).get('describe2'),
                  	  last1 = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex+2).get('itemWeight');	
                    }
                    if(first1&&!last1){
                    	//meta.css += 'row-span' + '' +  '';
                    }else{
                    	meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    }
                    
                    if (first) {
                        var i = rowIndex + 1;
                        var j = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('itemWeight')
                        		&& store.getAt(i).get('describe2') === store.getAt(i-1).get('describe2')) {
                         		i++;		
                        }

                        var rowHeight = 20, padding = 6,
                        height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';line-height:' + height + ';"';
                    }
                    return first ? value : '';
                },
dataIndex:'itemWeight',
width:40,
editor: new fm.NumberField({
                allowBlank: false,
                allowNegative: false
            })
},
{header:'因素说明',
	sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('describe3'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('describe3');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('describe3')) {
                            i++;
                        }
                        //alert("i: "+i+" rowIndex:"+rowIndex);
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';white-space:normal;"';
                    }
                    return first ? value : '';
                },
dataIndex:'describe3',
width:1200,
editor: new fm.TextField({
                allowBlank: false
            })
}

]); 

var ds = new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'model/listModelItems.do?dataFlag=2',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ 
totalProperty:'total',  
root:'resultData'},[
{name:'serialNo'},
{name:'describe1'}, 
{name:'describe2'},  
{name:'describe3'},
{name:'itemDescribe'},
{name:'itemValue'},
{name:'itemWeight'}
]) 
}); 
ds.load(); 


var grid=new Ext.grid.EditorGridPanel({ 
id:'myCustomers',
stripeRows:true,//斑马线效果
title:'<div align="center">已添加的定性因素</div>', 
height:700, 
cm:cm,
store: ds, 
clicksToEdit: 2,
columnLines:true, 
cls: 'grid-row-span',
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            }  
                      
});

function afterEdit(obj){    //每次更改后，触发一次该事件  
	var row = obj.record;
	var col = obj.field;
	//alert(row.data.serialNo);
	//alert(col);
   //alert("orginalValue:"+obj.originalValue+",value:"+obj.value);  
   
	Ext.Ajax.request({
		url:'model/editQua.do?dataFlag=2',
		params : { serialNo: row.data.serialNo,
			describe2:row.data.describe2,
			field:col, 
			originalValue:obj.originalValue, 
			modifiedValue:obj.value
		},
		method:'POST',
		success:function(){
			Ext.MessageBox.alert("提示","修改成功！");
			grid.store.reload(); 
		},failure:function(){
			Ext.MessageBox.alert("提示", "修改失败！"); 
		}
	});
 
}  
grid.on("afteredit", afterEdit, grid); 

var panel =  new Ext.Panel({
renderTo:"panel",
height:920,
items:[addForm, grid]
});


}); 